package top.huhuiyu.springboot3.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import top.huhuiyu.springboot3.service.RedisService;
import top.huhuiyu.springboot3.util.JsonUtils;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class RedisServiceImpl implements RedisService {
    private final StringRedisTemplate template;

    @Override
    public Boolean has(String key) {
        return template.hasKey(key);
    }

    @Override
    public void remove(String key) {
        template.delete(key);
    }

    @Override
    public <T> void save(String key, T value, Integer timeout) {
        String svalue = value == null ? "" : JsonUtils.stringify(value);
        template.opsForValue().set(key, svalue, timeout, TimeUnit.SECONDS);
    }

    @Override
    public <T> void save(String key, T value) {
        String svalue = value == null ? "" : JsonUtils.stringify(value);
        template.opsForValue().set(key, svalue);
    }

    @Override
    public <T> T get(String key, Class<T> clazz) {
        String value = template.opsForValue().get(key);
        return JsonUtils.parse(value, clazz);
    }

    @Override
    public <T> void update(String key, T value) {
        if (!has(key)) {
            return;
        }
        ValueOperations<String, String> ops = template.opsForValue();
        long expire = Optional.ofNullable(template.getExpire(key)).orElse(0L);
        if (expire <= 0) {
            return;
        }
        ops.set(key, JsonUtils.stringify(value), expire, TimeUnit.SECONDS);
    }

}
